import { colorStr } from '@/utils/utils';
import { useCallback, useEffect, useState } from 'react';
import { history } from 'umi';
import styles from './index.less';

interface Props {
  ifHomePage: string;
  goods: any[];
}

const GoodsDiv: React.FC<Props> = ({ goods, ifHomePage }) => {
  const [goodsList, setGoodsList] = useState<any[]>([]);

  const imgManage = useCallback(() => {
    let arr: any[] = goods;
    goods.map((item, index: number) => {
      let curr = JSON.stringify(item.img)
        .replace('[', '')
        .replace(']', '')
        .replace(/"/g, '')
        .replace(/\\/g, '')
        .split(',');
      arr[index].img = curr[0];
    });
    setGoodsList(arr);
  }, [goods]);

  useEffect(() => {
    imgManage();
  }, [imgManage]);

  return (
    <div
      className={styles.container}
      style={{
        backgroundColor: ifHomePage === '1' ? '#fff' : ifHomePage === '2' ? '#f7f9fa' : 'none',
        padding: ifHomePage === '3' ? '21px 36px 0 44px' : '53px 41px 0 92px',
      }}
    >
      {goodsList.map((item: any) => {
        return (
          <div
            key={item.id}
            className={styles.goods}
            style={{ marginRight: ifHomePage === '1' ? 50 : 30 }}
          >
            <img
              src={`http://localhost:8090/dyh/upload_images/commodity/${item.img}`}
              alt={'加载失败'}
              className={styles.img}
              loading={'lazy'}
              onClick={() => {
                history.push({
                  pathname: 'commodity',
                  query: { lastRoute: ifHomePage === '1' ? '商城首页' : '商品浏览', id: item.id },
                });
              }}
            />
            <div className={styles.data}>
              <div style={{ color: colorStr(7), fontSize: 18 }}>{`￥${item.price}`}</div>
              <div className={styles.month}>{`月销：${item.month}`}</div>
            </div>
            <div
              className={styles.title}
              onClick={() => {
                history.push({
                  pathname: 'commodity',
                  query: { lastRoute: ifHomePage === '1' ? '商城首页' : '商品浏览', id: item.id },
                });
              }}
            >
              {item.title}
            </div>
            <div className={styles.companyname}>{`店铺：${item.companyname}`}</div>
          </div>
        );
      })}
    </div>
  );
};

export default GoodsDiv;
